<template>
  <div class="ai-chat-container" :class="{ 'ai-chat-open': isOpen }">
    <!-- Chat toggle button -->
    <div
      class="chat-toggle"
      :class="{ 'chat-toggle-open': isOpen }"
      @click="toggleChat"
    >
      <van-icon :name="isOpen ? 'close' : 'service-o'" size="24" />
    </div>

    <!-- Chat panel -->
    <div class="chat-panel">
      <div class="chat-header">
        <span>AI 学习助手</span>
        <div class="header-actions">
          <van-button
            type="primary"
            size="mini"
            @click="sendCurrentQuestion"
            :disabled="isLoading"
          >
            解析当前题目
          </van-button>
          <van-icon
            name="delete-o"
            @click="clearConversation"
            style="margin-left: 10px"
          />
        </div>
      </div>

      <div class="chat-messages" ref="messagesContainer">
        <div
          v-for="(message, index) in messages"
          :key="index"
          class="message"
          :class="
            message.role === 'user' ? 'user-message' : 'assistant-message'
          "
        >
          <div class="message-content">
            <div v-if="message.role === 'assistant'" class="avatar">
              <van-icon name="manager-o" size="20" />
            </div>
            <div class="text" v-html="formatMessage(message.content)"></div>
            <div v-if="message.role === 'user'" class="avatar user-avatar">
              <van-icon name="contact" size="20" />
            </div>
          </div>
          <!-- 为第一条助手消息添加提示词按钮 -->
          <div
            v-if="message.role === 'assistant' && index === 0 && props.context"
            class="suggestion-prompts"
          >
            <button
              v-for="(prompt, promptIndex) in suggestionPrompts"
              :key="promptIndex"
              class="prompt-button"
              @click="handlePromptClick(prompt)"
            >
              {{ prompt }}
            </button>
          </div>
        </div>

        <!-- Streaming response indicator -->
        <div v-if="isLoading" class="message assistant-message">
          <div class="message-content">
            <div class="avatar">
              <van-icon name="manager-o" size="20" />
            </div>
            <div
              class="text"
              v-if="currentResponse"
              v-html="formatMessage(currentResponse)"
            ></div>
            <div class="text" v-else>
              <div class="typing-indicator">
                <span></span>
                <span></span>
                <span></span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- Completely redesign chat input area -->
      <div class="chat-input">
        <div class="input-container">
          <input
            v-model="userInput"
            placeholder="请输入问题..."
            class="input-field"
            :disabled="isLoading"
            @keyup.enter="sendMessage"
          />
          <button
            class="send-button"
            :disabled="!userInput.trim() || isLoading"
            @click="sendMessage"
          >
            <van-loading v-if="isLoading" color="#ffffff" size="20px" />
            <span v-else>发送</span>
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, computed, watch } from "vue";
import { useStore } from "vuex";
import aiApi from "@/api/ai";
import { formatMarkdown } from "@/utils/markdown";
import { showNotify } from "vant";

const props = defineProps({
  context: {
    type: String,
    default: null,
  },
});

const store = useStore();
const isOpen = ref(false);
const messages = ref([]);
const userInput = ref("");
const isLoading = ref(false);
const currentResponse = ref("");
const messagesContainer = ref(null);
const abortController = ref(null);
const DEBUG = true; // Set to false in production

// 生成欢迎信息，包含题目上下文
const generateWelcomeMessage = () => {
  if (props.context) {
    return `你好，我是AI助手，可以帮你解答关于当前题目的问题。

${props.context}

你可以问我：`;
  }

  return "你好，我是AI助手，有什么我可以帮助你的吗？";
};

// 预设的提示词
const suggestionPrompts = ref([
  "这道题应该选择哪个选项？",
  "为什么这道题的答案是...？",
  "这个知识点的详细解释是什么？",
]);

// 处理点击提示词
const handlePromptClick = (prompt) => {
  userInput.value = prompt;
  sendMessage();
};

// 初始化欢迎消息
onMounted(() => {
  messages.value = [{ role: "assistant", content: generateWelcomeMessage() }];
});

// 更新欢迎消息
const updateContextMessage = (context) => {
  if (!context) return;

  // 如果对话刚开始，更新欢迎消息
  if (messages.value.length <= 2) {
    if (messages.value.length === 0) {
      messages.value = [
        { role: "assistant", content: generateWelcomeMessage() },
      ];
    } else {
      messages.value[0].content = generateWelcomeMessage();
    }
  }
};

// 监听题目变化
watch(
  () => props.context,
  (newContext, oldContext) => {
    if (newContext && newContext !== oldContext) {
      if (DEBUG) console.log("题目上下文已更新:", newContext);
      updateContextMessage(newContext);
    }
  },
  { immediate: true }
);

// 向AI发送当前题目解析请求
const sendCurrentQuestion = async () => {
  if (!props.context || isLoading.value) {
    showNotify({ type: "warning", message: "无法获取当前题目信息" });
    return;
  }

  // 添加用户提问
  const userMessage =
    "请详细解析这道题目，分析各个选项的正确性，并说明正确答案是什么？";
  messages.value.push({ role: "user", content: userMessage });
  isLoading.value = true;
  currentResponse.value = "";

  // 滚动到底部
  await nextTick();
  scrollToBottom();

  try {
    // 格式化历史记录
    const history = messages.value
      .slice(0, -1) // 排除最新消息
      .map((msg) => ({
        role: msg.role,
        content: msg.content,
      }));

    // 获取用户ID
    const userId = store.getters.userId || localStorage.getItem("userId");

    // 构建增强的提示
    const enhancedPrompt = `${props.context}\n\n请详细解析这道题目，分析各个选项的正确性，并说明正确答案。`;

    if (DEBUG) console.log("发送题目解析请求:", enhancedPrompt);

    // 取消之前的请求
    if (abortController.value) {
      abortController.value.abort();
    }

    // 发送新请求
    abortController.value = aiApi.streamChat(
      enhancedPrompt,
      history,
      userId,
      handleResponseChunk,
      handleResponseComplete,
      handleResponseError
    );
  } catch (error) {
    console.error("发送解析请求时出错:", error);
    handleError(error);
  }
};

// 处理流式响应片段
const handleResponseChunk = (content) => {
  if (
    typeof content === "string" &&
    content.trim().startsWith("{") &&
    content.includes('"content"')
  ) {
    try {
      const parsedContent = JSON.parse(content);
      if (parsedContent && parsedContent.content) {
        currentResponse.value = parsedContent.content;
      } else {
        currentResponse.value = content; // 如果解析后没有content属性，使用原始内容
      }
    } catch (e) {
      // 如果解析失败，使用原始内容
      currentResponse.value = content;
    }
  } else {
    // 如果不是JSON对象字符串，直接使用
    currentResponse.value = content;
  }
  scrollToBottom();
};

// 处理完整响应
const handleResponseComplete = (finalContent) => {
  if (!finalContent) {
    if (!currentResponse.value || currentResponse.value.trim() === "") {
      finalContent = "抱歉，没有收到完整回复，请重试。";
    } else {
      finalContent = currentResponse.value;
    }
  }

  messages.value.push({ role: "assistant", content: finalContent });
  currentResponse.value = "";
  isLoading.value = false;
  abortController.value = null;
  scrollToBottom();
};

// 处理响应错误
const handleResponseError = (error) => {
  console.error("AI响应错误:", error);
  handleError(error);
};

// 统一的错误处理函数
const handleError = (error) => {
  // 检查是否是JSON解析错误
  const isJsonError =
    error.message &&
    (error.message.includes("JSON.parse") ||
      error.message.includes("unexpected end") ||
      error.message.includes("Unexpected token"));

  try {
    messages.value.push({
      role: "assistant",
      content: "连接AI服务出现问题，正在尝试备用连接方式...",
    });

    // 使用非流式API作为备用
    aiApi
      .chatWithAi(
        userInput.value,
        messages.value
          .slice(0, -2)
          .map((msg) => ({ role: msg.role, content: msg.content })),
        store.getters.userId || localStorage.getItem("userId")
      )
      .then((response) => {
        if (response && response.data && response.data.content) {
          messages.value.pop(); // 移除"尝试备用连接"消息
          messages.value.push({
            role: "assistant",
            content: response.data.content,
          });
        } else {
          messages.value.pop();
          messages.value.push({
            role: "assistant",
            content: "抱歉，我遇到了一些问题，请稍后再试。",
          });
        }
      })
      .catch((backupError) => {
        console.error("备用方法也失败:", backupError);

        // 构建更友好的错误消息
        let errorMsg = "抱歉，AI服务暂时不可用，请稍后再试。";

        if (isJsonError) {
          errorMsg += "\n\n可能是服务器返回了不正确的数据格式。";
        } else if (error.message && error.message.includes("Network Error")) {
          errorMsg += "\n\n网络连接问题，请检查您的网络连接。";
        } else {
          errorMsg += `\n\n错误详情: ${error.message || "未知错误"}`;
        }

        messages.value.pop();
        messages.value.push({
          role: "assistant",
          content: errorMsg,
        });
      })
      .finally(() => {
        isLoading.value = false;
        currentResponse.value = "";
        scrollToBottom();
      });
  } catch (fallbackError) {
    console.error("备用方法异常:", fallbackError);
    messages.value.push({
      role: "assistant",
      content: "抱歉，AI服务暂时不可用，请稍后再试。",
    });
    isLoading.value = false;
    currentResponse.value = "";
    scrollToBottom();
  }
};

// Toggle chat panel
const toggleChat = () => {
  isOpen.value = !isOpen.value;
  if (isOpen.value) {
    nextTick(() => {
      scrollToBottom();
    });
  }
};

// Format message with markdown
const formatMessage = (content) => {
  try {
    return formatMarkdown(content);
  } catch (e) {
    console.error("Error formatting message:", e);
    return content;
  }
};

// Clear conversation history
const clearConversation = async () => {
  try {
    // Get user ID for conversation caching if available
    const userId = store.getters.userId || localStorage.getItem("userId");

    if (userId) {
      // Call API to clear server-side cache
      await aiApi.clearConversation(userId);
    }

    // Reset local messages with context if available
    messages.value = [{ role: "assistant", content: generateWelcomeMessage() }];

    // Scroll to bottom
    scrollToBottom();
  } catch (error) {
    console.error("Error clearing conversation:", error);
    // Add an error message
    messages.value.push({
      role: "assistant",
      content: "清空对话失败，请稍后再试。",
    });
  }
};

// Scroll to bottom of messages
const scrollToBottom = () => {
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
  }
};

// Send a message to the AI
const sendMessage = async () => {
  const userMessage = userInput.value.trim();
  if (!userMessage || isLoading.value) return;

  // Add user message to chat
  messages.value.push({ role: "user", content: userMessage });
  userInput.value = "";
  isLoading.value = true;
  currentResponse.value = "";

  // Scroll to bottom
  await nextTick();
  scrollToBottom();

  try {
    // Format history for API
    const history = messages.value
      .slice(0, -1) // Exclude the latest user message
      .map((msg) => ({
        role: msg.role,
        content: msg.content,
      }));

    // Get user ID for conversation caching if available
    const userId = store.getters.userId || localStorage.getItem("userId");

    // 检测是否是关于当前题目的问题
    const isQuestionRelated =
      /这道题|这个题|当前题|这题|选哪个|哪个选项|答案是什么|为什么选/.test(
        userMessage
      );

    // 构建提示词
    let prompt = userMessage;
    if (isQuestionRelated && props.context) {
      prompt = `${props.context}\n\n用户问题：${userMessage}`;
      if (DEBUG) console.log("添加题目上下文到用户提问");
    }

    if (DEBUG) {
      console.log("发送AI聊天请求:");
      console.log("提示词:", prompt);
      console.log("历史:", history);
      console.log("用户ID:", userId);
    }

    // Abort previous request if exists
    if (abortController.value) {
      abortController.value.abort();
    }

    // Start new request
    abortController.value = aiApi.streamChat(
      prompt,
      history,
      userId, // Pass userId for caching
      handleResponseChunk,
      handleResponseComplete,
      handleResponseError
    );
  } catch (error) {
    console.error("Error sending message:", error);
    handleError(error);
  }
};

onMounted(() => {
  // Initialize any required data
  window.addEventListener("resize", scrollToBottom);
});
</script>

<style scoped>
.ai-chat-container {
  position: fixed;
  right: 20px;
  bottom: 70px; /* Position above action bar */
  z-index: 1000;
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  max-height: 80vh;
}

.chat-toggle {
  width: 50px;
  height: 50px;
  border-radius: 25px;
  background: linear-gradient(135deg, #4facfe, #00f2fe);
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  box-shadow: 0 4px 12px rgba(0, 114, 255, 0.3);
  color: white;
  transition: all 0.3s ease;
  z-index: 1002;
}

.chat-toggle-open {
  transform: rotate(45deg);
  background: linear-gradient(135deg, #ff6b6b, #ff8e8e);
}

.chat-panel {
  position: absolute;
  bottom: 60px;
  right: 0;
  width: 90vw;
  max-width: 360px;
  height: 70vh;
  max-height: calc(100vh - 180px);
  background-color: white;
  border-radius: 16px;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  overflow: hidden;
  transform: scale(0);
  transform-origin: bottom right;
  transition: transform 0.3s ease;
  z-index: 1001;
}

.ai-chat-open .chat-panel {
  transform: scale(1);
}

.chat-header {
  padding: 16px;
  background: linear-gradient(to right, #4facfe, #00f2fe);
  color: white;
  font-weight: bold;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-radius: 16px 16px 0 0;
}

.header-actions {
  display: flex;
  align-items: center;
}

.chat-messages {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
  background-color: #f8f9fa;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.message {
  max-width: 85%;
  display: flex;
  flex-direction: column;
}

.user-message {
  align-self: flex-end;
}

.assistant-message {
  align-self: flex-start;
}

.message-content {
  display: flex;
  align-items: flex-start;
  gap: 8px;
}

.avatar {
  width: 36px;
  height: 36px;
  border-radius: 18px;
  background-color: #e1f5fe;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #29b6f6;
  flex-shrink: 0;
}

.user-avatar {
  background-color: #e3f2fd;
  color: #42a5f5;
}

.text {
  padding: 12px;
  border-radius: 12px;
  background-color: white;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  font-size: 14px;
  line-height: 1.5;
  white-space: pre-wrap;
  word-break: break-word;
}

.user-message .text {
  background-color: #e3f2fd;
  margin-right: 8px;
}

.chat-input {
  padding: 12px 12px 12px 12px;
  border-top: 1px solid #eee;
  background-color: white;
  width: 100%;
  box-sizing: border-box;
}

.input-container {
  display: flex;
  width: 100%;
  height: 40px;
  align-items: center;
  box-sizing: border-box;
}

.input-field {
  flex: 1;
  min-width: 0;
  height: 100%;
  padding: 0 10px;
  margin-right: 8px;
  border: 1px solid #e8e8e8;
  border-radius: 20px;
  background-color: #f5f7fa;
  font-size: 14px;
  outline: none;
  box-sizing: border-box;
}

.input-field:focus {
  border-color: #4facfe;
}

.input-field:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.send-button {
  min-width: 56px;
  width: auto;
  padding: 0 10px;
  height: 36px;
  margin-left: 0;
  background: linear-gradient(to right, #4facfe, #00f2fe);
  color: white;
  border: none;
  border-radius: 18px;
  font-size: 14px;
  cursor: pointer;
  display: flex;
  justify-content: center;
  align-items: center;
  transition: opacity 0.2s;
  white-space: nowrap;
  flex-shrink: 0;
}

.send-button:hover {
  opacity: 0.9;
}

.send-button:disabled {
  background: #cccccc;
  cursor: not-allowed;
}

/* Typing indicator animation */
.typing-indicator {
  display: flex;
  align-items: center;
  gap: 4px;
}

.typing-indicator span {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: #bbbfc4;
  display: inline-block;
  animation: typing 1.4s infinite ease-in-out both;
}

.typing-indicator span:nth-child(1) {
  animation-delay: 0s;
}

.typing-indicator span:nth-child(2) {
  animation-delay: 0.2s;
}

.typing-indicator span:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes typing {
  0%,
  100% {
    transform: scale(0.7);
    opacity: 0.5;
  }
  50% {
    transform: scale(1);
    opacity: 1;
  }
}

/* Dark mode support */
@media (prefers-color-scheme: dark) {
  .chat-panel {
    background-color: #1a1a1a;
  }

  .chat-messages {
    background-color: #121212;
  }

  .text {
    background-color: #2c2c2c;
    color: #e0e0e0;
  }

  .user-message .text {
    background-color: #0d47a1;
    color: #ffffff;
  }

  .avatar {
    background-color: #1a1a1a;
  }

  .chat-input {
    background-color: #1a1a1a;
    border-top-color: #333;
  }

  .input-field {
    background-color: #2c2c2c;
    border-color: #444;
    color: #e0e0e0;
  }

  .input-field:focus {
    border-color: #00f2fe;
  }

  .send-button:disabled {
    background: #444444;
  }
}

/* 提示词按钮样式 */
.suggestion-prompts {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-top: 10px;
  margin-left: 44px; /* 与消息内容对齐 */
}

.prompt-button {
  background-color: #f0f7ff;
  border: 1px solid #e0ebfa;
  border-radius: 18px;
  padding: 8px 12px;
  font-size: 13px;
  color: #4a90e2;
  cursor: pointer;
  text-align: left;
  transition: all 0.2s ease;
  max-width: 280px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.prompt-button:hover {
  background-color: #e3f2fd;
  border-color: #90caf9;
}

/* Dark mode support */
@media (prefers-color-scheme: dark) {
  .prompt-button {
    background-color: #1e3a5f;
    border-color: #2c4a6f;
    color: #90caf9;
  }

  .prompt-button:hover {
    background-color: #25476f;
    border-color: #3a5f8a;
  }
}
</style>
